<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2020 All rights reserved.
// +----------------------------------------------------------------------
// | User: Simony <1362229026@qq.com>
// | wechat: Shen86579595
// +----------------------------------------------------------------------

namespace app\common\logic;

use OSS\OssClient;
use OSS\Core\OssException;
use think\Db;

class BonusLogic
{

    public $vip_level = 2;   //vip等级是

    /**
     * User: Simony
     * Function:结算推荐奖
     * @param $member_id 认证的会员
     * @return array|void
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function recommendBonus($member_id)
    {

        $flag_id = 0; //这个做未奖金状态标识id
        $bonus_field = 'recommend_money';//奖金字段
        $periods = $this->getPeriods() + 1; //期号
        $current_time = time(); //计算奖金时间

        $memberModel = model('common/member/Member');
        $member = $memberModel->getInfoById($member_id);
        if (!$member) return ds_arr(ERROR, '当前用户不存在');

        $config = moduleConfig('extension');
        if (!isset($config['g'])) return ds_arr(SUCCESS, '');

        $max_generate = max($config['g'][1], $config['g'][2]);

        $recommend_arr = explode(',', $member['recommend_str']);
        $recommend_arr = array_slice($recommend_arr, 1, $max_generate); //截取n代(不包括自己)

        $field = 'id,sex,real_verify,video_verify,status,level';
        $member_list = $memberModel->getCol($field, ['id' => $recommend_arr]);


        $check_state = $this->checkState($member['id'], $bonus_field, $flag_id);
        if (isset($check_state['code']) && $check_state['code'] != SUCCESS) return ds_arr($check_state['code'], $check_state['msg'], $check_state['result']);
        if ($check_state != false) return ds_arr(SUCCESS, '请勿重复结算推广奖'); //


        foreach ($recommend_arr as $k => $mid) {
            $generate = $k + 1; //代数

            $superior_member = isset($member_list[$mid]) ? $member_list[$mid] : [];
            if (empty($superior_member)) continue;
            if ($superior_member['status'] == 0) continue; //账户禁用了

            if (isset($config['is_vip'][$superior_member['sex']][$generate])) {
                $is_vip = $config['is_vip'][$superior_member['sex']][$generate];
                if ($is_vip == 1 && $superior_member['level'] >= $this->vip_level) continue; //满足不了实名条件
            }

            if (isset($config['is_realname'][$superior_member['sex']][$generate])) { //设置了进去
                if ($superior_member['real_verify'] < $config['is_realname'][$superior_member['sex']][$generate]) continue; //满足不了实名条件
            }

            if (isset($config['val'][$superior_member['sex']][$generate][$member['sex']])) {
                $award = $config['val'][$superior_member['sex']][$generate][$member['sex']]; //[val][上级性别即1][上级代数][下级性别]
                $award = $award > 0 ? $award : 0;
            } else {
                $award = 0;
            }

            if ($award <= 0) continue;
            $source = $member['nickname'] . '[' . $generate . '代]已完成实名认证,奖励您' . $award . '金币';


            $param[$superior_member['id']] = array('bonus_field' => $bonus_field, 'award' => $award);//回滚奖金的数据
            $res = $this->settlementBonus($superior_member['id'], $member['id'], $bonus_field, $award, $current_time, $periods, $param, $source, model('common/bonus/Bonus')::SECOND_GRANT); //结算奖金

            if (isset($res['code']) && $res['code'] != SUCCESS) return ds_arr($res['code'], $res['msg'], $res['result']);
        }

        $bonusStatusModel = model('common/bonus/BonusStatus');
        $res = $bonusStatusModel->edit(['member_id' => $member_id, 'bonus_field' => $bonus_field, 'flag_id' => $flag_id], ['state' => 1]);

        return $res ? ds_arr(SUCCESS, '奖金发放完毕') : ds_arr(ERROR, '奖金发放失败');

    }

    /**
     * User: Simony
     * Function:结算佣金奖 （购买套餐）
     * @param $member_id 会员id
     * @param int $moeny 币量
     * @param int $flag_id 奖金状态标识id ()
     * @return array|void
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function commissionBonus($member_id, $package_id)
    {
        $bonus_field = 'commission_money';//奖金字段
        $periods = $this->getPeriods() + 1; //期号
        $current_time = time(); //计算奖金时间

        $memberModel = model('common/member/Member');
        $member = $memberModel->getInfoById($member_id);
        if (!$member) return ds_arr(ERROR, '当前用户不存在');

        $packageModel = model('common/package/Package');
        $package = $packageModel->getInfoByID($package_id);
        if (!$package) return ds_arr(ERROR, '当前套餐不存在');
        $moeny = $package['price'];

        $config = moduleConfig('commission');
        if (!isset($config['g'])) return ds_arr(SUCCESS, '');

        $max_generate = max($config['g'][1], $config['g'][2]);

        $recommend_arr = explode(',', $member['recommend_str']);
        $recommend_arr = array_slice($recommend_arr, 1, $max_generate); //截取n代

        $field = 'id,sex,real_verify,video_verify,status,level';
        $member_list = $memberModel->getCol($field, ['id' => $recommend_arr]);

        foreach ($recommend_arr as $k => $mid) {
            $generate = $k + 1; //代数

            $superior_member = isset($member_list[$mid]) ? $member_list[$mid] : [];
            if (empty($superior_member)) continue;
            if ($superior_member['status'] == 0) continue; //账户禁用了

            //[is_vip][上级性别即1][上级代数]
            if (isset($config['is_vip'][$superior_member['sex']][$generate])) {
                $is_vip = $config['is_vip'][$superior_member['sex']][$generate];
                if ($is_vip == 1 && $superior_member['level'] >= $this->vip_level) continue; //满足不了实名条件
            }

            //[is_realname][上级性别即1][上级代数]
            if (isset($config['is_realname'][$superior_member['sex']][$generate])) { //设置了进去
                if ($superior_member['real_verify'] < $config['is_realname'][$superior_member['sex']][$generate]) continue; //满足不了实名条件
            }

            if (isset($config['val'][$superior_member['sex']][$generate][$member['sex']])) {
                $percent = $config['val'][$superior_member['sex']][$generate][$member['sex']] / 100; //[val][上级性别即1][上级代数][下级性别]
            } else {
                $percent = 0; //0
            }
            $award = round($moeny * $percent, 0);

            if ($award <= 0) continue;
            $source = $member['nickname'] . '[' . $generate . '代] 购买' . $package['name'] . '消费了' . $moeny . '金币,奖励您' . $award . '金币';
            $param[$superior_member['id']] = ['bonus_field' => $bonus_field, 'award' => $award];//回滚奖金的数据
            $res = $this->settlementBonus($superior_member['id'], $member['id'], $bonus_field, $award, $current_time, $periods, $param, $source, model('common/bonus/Bonus')::SECOND_GRANT); //结算奖金
            if (isset($res['code']) && $res['code'] != SUCCESS) return ds_arr($res['code'], $res['msg'], $res['result']);
        }

        return ds_arr(SUCCESS, '奖金发放完毕');


    }


    /**
     * User: Simony
     * Function:合伙人奖
     * @param $member_id
     */
    public function partnerBonus($member_id, $package_id)
    {
        $flag_id = 0; //这个做未奖金状态标识id
        $bonus_field = 'partner_money';//奖金字段
        $periods = $this->getPeriods() + 1; //期号
        $current_time = time(); //计算奖金时间

        $memberModel = model('common/member/Member');
        $member = $memberModel->getInfoById($member_id);
        if (!$member) return ds_arr(ERROR, '当前用户不存在');

        $packageModel = model('common/package/Package');
        $package = $packageModel->getInfoByID($package_id);
        if (!$package) return ds_arr(ERROR, '当前套餐不存在');
        $moeny = $package['price'];


        $partner = moduleConfig('partner');
        if (!isset($partner[$memberModel::PARTNER])) return ds_arr(SUCCESS, '');
        $percent = $partner[$memberModel::PARTNER] / 100;

        $superior_ids = explode(',', $member['recommend_str']);
        array_shift($superior_ids);

        $superior_list = $memberModel->getList([['id','in',implode(',',$superior_ids)],['identity','gt',0]], 0);
        if (empty($superior_list)) return ds_arr(SUCCESS, '');

        foreach ($superior_list as $superior_member) {
            $percent = $partner[$superior_member['identity']] / 100;
            $award = round($moeny * $percent, 0);
            if ($award <= 0) continue;
            $source = $member['nickname'] . '购买' . $package['name'] . '消费了' . $moeny . '金币,合伙人收益' . $award . '金币';
            $param[$superior_member['id']] = ['bonus_field' => $bonus_field, 'award' => $award];//回滚奖金的数据
            $res = $this->settlementBonus($superior_member['id'], $member['id'], $bonus_field, $award, $current_time, $periods, $param, $source, model('common/bonus/Bonus')::SECOND_GRANT); //结算奖金
            if (isset($res['code']) && $res['code'] != SUCCESS) return ds_arr($res['code'], $res['msg'], $res['result']);
        }
        return ds_arr(SUCCESS, '奖金发放完毕');

    }


    /**
     * User: Simony
     * Function:获取奖金期号
     * @return int
     */
    public function getPeriods()
    {
        $bonusModel = model('common/bonus/Bonus');
        $periods = $bonusModel->getMax([], 'periods');
        return intval($periods);
    }


    /**
     * User: Simony
     * Function:结算奖金
     * @param $member_id 会员id
     * @param $relation_member_id 关联用户id
     * @param $bonus_field 奖金名称字段
     * @param $money 奖金
     * @param $modtime 时间
     * @param $periods 期号
     * @param $jsparams 回滚数据
     * @param $source 描述来源
     * @param $grant_type 方法方式 0秒发 、1日发 、2周发、3月发
     * @return array|bool|void
     */
    public function settlementBonus($member_id, $relation_member_id, $bonus_field, $money, $modtime, $periods, $jsparams, $source, $grant_type = 0)
    {
        $memberModel = model('common/member/Member');
        $member = $memberModel->getInfoById($member_id);
        if (empty($member)) return;
        $state = 0; //状态：0正常，1停发
        $done = 0;//是否发放：0未发放，1已发放
        $netincome = $money; //以后这里可能扣除费率等等


        $bonusModel = model('common/bonus/Bonus');
        $bonus = $bonusModel->getInfo(['member_id' => $member_id, 'periods' => $periods]);


        if ($bonus) {
            $source = $bonus['source'] . '\n' . $source;
            if (!empty($bonus['jsparams'])) {
                $params = json_decode($bonus['jsparams'], TRUE);
                $jsparams = $params + $jsparams; //数组合并
            }
            $params = json_encode($jsparams);
            $where = ['id' => $bonus['id'], 'periods' => $periods];
            $update_data = [
                $bonus_field => Db::Raw("{$bonus_field}+{$money}"),
                'params' => $params,
                'netincome' => Db::Raw("netincome+{$netincome}"),
                'money' => Db::Raw("money+{$money}"),
                'done' => $done,
                'state' => $state,
                'source' => $source,
                'member_id' => $member_id,
                'relation_member_id' => $relation_member_id,
                'periods' => $periods,
                'create_time' => $modtime,
                'grant_type' => $grant_type
            ];
            $res = $bonusModel->edit($where, $update_data);
            return $res ? true : ds_arr(ERROR, '结算奖金失败1');
        } else {
            $params = json_encode($jsparams);
            $add_data = [
                $bonus_field => $money,
                'params' => $params,
                'netincome' => $netincome,
                'money' => $money,
                'state' => $state,
                'source' => $source,
                'member_id' => $member_id,
                'relation_member_id' => $relation_member_id,
                'periods' => $periods,
                'create_time' => $modtime,
                'grant_type' => $grant_type
            ];
            $res = $bonusModel->add($add_data);
            return $res ? true : ds_arr(ERROR, '结算奖金失败2');
        }
    }

    /**
     * User: Simony
     * Function:校验奖金状态
     * @param $member_id
     * @param $bonus_field
     * @param int $flag_id
     * @return array|bool
     */
    public function checkState($member_id, $bonus_field, $flag_id = 0)
    {
        $bonusStatusModel = model('common/bonus/BonusStatus');
        $where = ['member_id' => $member_id, 'bonus_field' => $bonus_field, 'flag_id' => $flag_id];
        $bonusStatus = $bonusStatusModel->getInfo($where);
        if (empty($bonusStatus)) {
            //插入一条记录
            $add_data = [
                'member_id' => $member_id,
                'bonus_field' => $bonus_field,
                'state' => 0,
                'flag_id' => $flag_id
            ];
            $res = $bonusStatusModel->add($add_data);

            return $res ? false : ds_arr(ERROR, '添加奖金状态记录失败1');
        }
        return $bonusStatus['state'] == 0 ? false : true;

    }

    /**
     * User: Simony
     * Function:发放奖金 0秒发 、1日发 、2周发、3月发
     * @param int $putout
     */
    public function grantBonus($grant_type = 0)
    {
        $bonusModel = model('common/bonus/Bonus');
        $memberLogic = model('common/member/MemberLogic', 'logic');

        $field = 'id,member_id,netincome,source,relation_member_id,source';
        $where = ['grant_type' => $grant_type, 'state' => 0, 'done' => 0];
        $bonus_list = $bonusModel->getCol($field, $where);

        foreach ($bonus_list as $bonus) {
            $update_available_balance_res = $memberLogic->updateAvailableBalance($bonus['member_id'], $bonus['netincome'], 0, 4, $bonus['source'], $bonus['relation_member_id']);
            if ($update_available_balance_res['code'] != SUCCESS) return ds_arr($update_available_balance_res['code'], $update_available_balance_res['msg']);
            model('common/Noticle', 'logic')->sendTxtSysNotice($bonus['member_id'], $bonus['source'], 6);
        }

        $id_arr = array_keys($bonus_list);
        $update_data = ['done' => 1, 'grant_time' => time()];
        $res = $bonusModel->edit(['id' => $id_arr], $update_data);
        return $res ? ds_arr(SUCCESS, '发放奖金成功') : ds_arr(ERROR, '发放奖金失败');
    }
}
